using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;



namespace Engine.Factory
{
    public class CSVDonloader
    {
        static public void GetCSV()
        {
            
            //http://el-toro.ath.cx/csv2/bin/retrieve?trigger=CLSADVD27&name=/ClubSandy-DVD027(Final)_2638.zip
            WebResponse registrationKey = null;
            String url_string = "http://el-toro.ath.cx/csv2/bin/retrieve"
                                + "?trigger=" + System.Web.HttpUtility.UrlEncode("CLSADVD24")
                                + "&name=" + System.Web.HttpUtility.UrlEncode("/ClubSandy-DVD024(Final)_2723.zip");
            try
            {
                WebRequest requestRegistration = WebRequest.Create(url_string);
                registrationKey = requestRegistration.GetResponse();
            }
            catch (Exception ex)
            {
                return;
            }

            Stream stream = registrationKey.GetResponseStream();


            StreamReader reader = new StreamReader(stream);
            FileStream file = new FileStream("c:\\ff.zip", FileMode.Create);
            int bb;
            while((bb = stream.ReadByte()) != -1)
            {
                file.WriteByte((byte)bb);
            }
            
            //String s = reader.ReadToEnd();
            
            StreamWriter sw = new StreamWriter("c:\\ff1.zip");

            //while(reader.Peek() >= 0)
            {
            //    sw.Write((byte)reader.Read());
            }

            



using (ZipInputStream s = new ZipInputStream(stream)) 
{

			ZipEntry theEntry;
			while ((theEntry = s.GetNextEntry()) != null) {
				
				Console.WriteLine(theEntry.Name);
				
				string directoryName = Path.GetDirectoryName(theEntry.Name);
				string fileName      = Path.GetFileName(theEntry.Name);
				
				// create directory
				if ( directoryName.Length > 0 ) {
					Directory.CreateDirectory(directoryName);
				}
				
				if (fileName != String.Empty) {
					using (FileStream streamWriter = File.Create(theEntry.Name)) {
					
						int size = 2048;
						byte[] data = new byte[2048];
						while (true) {
							size = s.Read(data, 0, data.Length);
							if (size > 0) {
								streamWriter.Write(data, 0, size);
							} else {
								break;
							}
						}
					}
				}
			}
}








            reader.Close();
            sw.Close();
            file.Close();

        }
    }
}
